# base_model.py
from src import db

# 常用列类型 & 约束
# String, Text, Integer, BigInteger, Float, Boolean, DateTime, Enum
# primary_key, nullable, unique, index, default, server_default, autoincrement

# 会话（Session）快捷
# db.session.add(obj)            # 插入
# db.session.add_all([...])      # 批量插入
# db.session.delete(obj)         # 删除
# db.session.commit()            # 提交事务
# db.session.flush()             # 立即发 SQL，但不 commit
# db.session.rollback()          # 回滚

# 查询（Query Interface）·
# 目的	写法示例
# 主键查询	User.query.get(pk)
# 取第一条 / 唯一一条	.first() / .one() / .one_or_none()
# 条件过滤	.filter(User.name=='bob') / .filter_by(name='bob')
# 模糊 / 范围	.filter(User.name.like('%bo%')), .between(18, 30)
# 排序	.order_by(User.age.desc())
# 分页	.paginate(page=1, per_page=20, error_out=False)
# 计数	.count()
# 只选部分列	db.session.query(User.id, User.name).all()
# 原生 SQL / text	db.session.execute(text('SELECT * FROM users WHERE id=:uid'), {'uid': 1})


class BaseModel(db.Model):
    __abstract__ = True  # 关键：标记为抽象类

    id = db.Column(db.BigInteger, primary_key=True, info={"description": "主键"})
    status = db.Column(db.SmallInteger, nullable=False, server_default=db.FetchedValue(), info={"description": "状态"})
    gmt_create = db.Column(
        db.DateTime, nullable=False, server_default=db.FetchedValue(), info={"description": "创建时间"}
    )
    gmt_modified = db.Column(
        db.DateTime, nullable=False, server_default=db.FetchedValue(), info={"description": "修改时间"}
    )

    def model_dump(self, include=None, exclude=None):
        include = include or self.__table__.columns.keys()
        if exclude:
            include = [k for k in include if k not in exclude]
        return {k: getattr(self, k) for k in include}
